package com.book.shop.model.form;

import com.book.shop.config.ByteArrayMultipartFile;
import com.book.shop.model.Book;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
public class BookForm  implements Serializable {
    private Long bookId;
    private String bookName;
    private String bookAuthor;
    private String bookIsbn;
    private String bookPublisher;
    private String bookDescription;
    private BigDecimal bookPrice;
    private MultipartFile bookImage;
    private String imageContentType;


    public BookForm(Book book) {
        this.bookId=book.getBookId();
        this.bookName = book.getBookName();
        this.bookAuthor = book.getBookAuthor();
        this.bookIsbn=book.getBookIsbn();
        this.bookPublisher=book.getBookPublisher();
        this.bookPrice =book.getBookPrice();
        this.bookDescription=book.getBookDescription();

        // 处理 byte[] 转换为 MultipartFile
        this.bookImage = new ByteArrayMultipartFile(
                book.getBookImage(),
                null,
                book.getBookImageContentType()
        );
    }
    public void setBookImage(MultipartFile bookImage) {
        this.bookImage = bookImage;
    }
    public BookForm(){

    }
    public Book toBook(Book book) {
        book.setBookId(this.bookId);
        book.setBookName(this.bookName);
        book.setBookAuthor(this.bookAuthor);
        book.setBookIsbn(this.bookIsbn);
        book.setBookPrice(this.bookPrice);
        book.setBookDescription(this.bookDescription);
        book.setBookPublisher(this.bookPublisher);
        try {
            if (this.bookImage != null && !this.bookImage.isEmpty()) {
                book.setBookImage(this.bookImage.getBytes());
                book.setBookImageContentType(this.bookImage.getContentType());
            }
        } catch (IOException e) {
            // 处理异常，例如记录日志或抛出自定义异常
            // 这里简单地打印异常信息
            e.printStackTrace();
            // 可以选择抛出自定义异常
        }
        return book;
    }
}
